<?php
namespace CRM\Model;

//向企业微信API发送请求，处理企业微信的回调的模型
class WXWorkModel{
    public $corpID;
    public $secret;
    public $host="https://qyapi.weixin.qq.com/cgi-bin/";
    function __construct(){
        $this->corpID=C("CorpID");
        $this->secret=C("Secret");
    }
    public function getToken(){
        $token=S("WXWorkToken");
        if($token){
            return $token;
        }
        $url=$this->host."gettoken?corpid=".$this->corpID."&corpsecret=".$this->secret;
        $response=$this->get($url);
        S("WXWorkToken",$response["access_token"],$response["expires_in"]);
        return $response["access_token"];
    }
    public function getDepartmentList($id=""){
        $url=$this->host."department/list?access_token=".$this->getToken();
        if($id){
            $url.="&id=".$id;
        }
        $response=$this->get($url);
        return $response["department"];
    }
    public function getSimpleUserList($departmentID,$fetchChild=0){
        $url=$this->host."user/simplelist?access_token=".$this->getToken()."&department_id=$departmentID&fetch_child=$fetchChild";
        $response=$this->get($url);
        return $response["userlist"];
    }
    public function getUserList($departmentID,$fetchChild=0){
        $url=$this->host."user/list?access_token=".$this->getToken()."&department_id=$departmentID&fetch_child=$fetchChild";
        $response=$this->get($url);
        return $response["userlist"];
    }
    public function get($url){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, true);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        $output = curl_exec($ch);
        curl_close($ch);
        if(!$output){
            $this->error="curl error:".curl_errno($ch)." message:".curl_error($ch);
            return false;
        }
        return $this->parseData($output);
    }
    public function parseData($output){
        $response=json_decode($output,true);
        if($response["errcode"]!==0){
            $this->error=$response["errmsg"];
            return false;
        }
        return $response;
    }
}